package cn.com.cifi.mars.service.impl;

import cn.com.cifi.mars.bean.vo.price.ApprovedDiffDetailVO;
import cn.com.cifi.mars.constant.CollectTypeEnum;
import cn.com.cifi.mars.constant.OrgTypeEunm;
import cn.com.cifi.mars.entity.ApprovalVersionCompare;
import cn.com.cifi.mars.entity.PriceApprovalDifferencesDetail;
import cn.com.cifi.mars.mapper.mars.ApprovalVersionCompareMapper;
import cn.com.cifi.mars.mapper.mars.PriceApprovalDifferencesDetailMapper;
import cn.com.cifi.mars.service.PriceApprovalDifferencesDetailService;
import cn.com.cifi.mars.service.SubmitApprovedProjectService;
import cn.com.cifi.mars.util.UUIDUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 货值审批全盘差异详情表 服务实现类
 * </p>
 *
 * @author lyb
 * @since 2021-08-10
 */
@Service
public class PriceApprovalDifferencesDetailServiceImpl extends ServiceImpl<PriceApprovalDifferencesDetailMapper, PriceApprovalDifferencesDetail> implements PriceApprovalDifferencesDetailService {


    @Autowired
    private SubmitApprovedProjectService submitApprovedProjectService;

    @Autowired
    private ApprovalVersionCompareMapper approvalVersionCompareMapper;

    @Autowired
    private PriceApprovalDifferencesDetailMapper priceApprovalDifferencesDetailMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveData(String id, String projectId, String versionState) {
        List<ApprovalVersionCompare> approvalVersionCompares = approvalVersionCompareMapper.selectByKey(id);
        List<ApprovalVersionCompare> comparesTypeList = approvalVersionCompares.stream().filter(x -> !x.getCollectType().equals("adjust_after")).collect(Collectors.toList());
        List<PriceApprovalDifferencesDetail> resultList = new ArrayList<>();
        if (CollectionUtils.isEmpty(comparesTypeList)) {
            List<ApprovedDiffDetailVO> list = submitApprovedProjectService.differenceDetailResultData(projectId, id, "adjust_before");
            List<PriceApprovalDifferencesDetail> dataList = preparePriceApprovalDifferencesDetail(list, id, projectId, versionState, "adjust_before");
            resultList.addAll(dataList);
        } else {
            for (ApprovalVersionCompare com : comparesTypeList) {
                List<ApprovedDiffDetailVO> list = submitApprovedProjectService.differenceDetailResultData(projectId, id, com.getCollectType());
                List<PriceApprovalDifferencesDetail> dataList = preparePriceApprovalDifferencesDetail(list, id, projectId, versionState, com.getCollectType());
                resultList.addAll(dataList);
            }
        }

        if (CollectionUtils.isNotEmpty(resultList)) {
            priceApprovalDifferencesDetailMapper.insertBatch(resultList);
        }


    }

    @Override
    public List<PriceApprovalDifferencesDetail> selectByBillIdAndType(String businessKey, String type) {

        List<PriceApprovalDifferencesDetail> priceApprovalDifferencesDetails =
                priceApprovalDifferencesDetailMapper.selectList(new QueryWrapper<PriceApprovalDifferencesDetail>()
                        .eq("bill_id", businessKey)
                        .eq("vs_type", type)
                        .orderByAsc("stage_code")
                        .orderByAsc("group_code")
                        .orderByAsc("product_code")
                        .orderByDesc("create_time")
                        .groupBy("stage_code")
                        .groupBy("group_code")
                        .groupBy("product_code")
                        .groupBy("free_type_name")
                        .groupBy("pro_type_name"));

        return priceApprovalDifferencesDetails;
    }

    private List<PriceApprovalDifferencesDetail> preparePriceApprovalDifferencesDetail(List<ApprovedDiffDetailVO> list, String id, String projectId,
                                                                                       String versionState, String type) {
        List<PriceApprovalDifferencesDetail> dataList = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(list)) {
            for (ApprovedDiffDetailVO vo : list) {
                PriceApprovalDifferencesDetail detail = new PriceApprovalDifferencesDetail();
                if (vo.getPid().equals("0")) {
                    detail.setProjectId(projectId);
                    detail.setProjectCode(vo.getOrgCode());
                    detail.setProjectName(vo.getOrgName());
                } else if (vo.getType().equals(OrgTypeEunm.ORG_STAGE.getKey())) {
                    ApprovedDiffDetailVO parentObj = getParentObj(list, vo.getPid());
                    if (parentObj != null) {
                        detail.setProjectId(projectId);
                        detail.setProjectCode(parentObj.getOrgCode());
                        detail.setProjectName(parentObj.getOrgName());
                    }
                    detail.setStageCode(vo.getOrgCode());
                    detail.setStageName(vo.getOrgName());
                } else if (vo.getType().equals(OrgTypeEunm.ORG_GROUP.getKey())) {
                    ApprovedDiffDetailVO stageObj = getParentObj(list, vo.getPid());
                    if (stageObj != null) {
                        detail.setStageCode(stageObj.getOrgCode());
                        detail.setStageName(stageObj.getOrgName());
                        ApprovedDiffDetailVO projectObj = getParentObj(list, stageObj.getPid());
                        if (projectObj != null) {
                            detail.setProjectId(projectId);
                            detail.setProjectCode(projectObj.getOrgCode());
                            detail.setProjectName(projectObj.getOrgName());
                        }
                    }
                    detail.setGroupCode(vo.getOrgCode());
                    detail.setGroupName(vo.getOrgName());
                } else {
                    ApprovedDiffDetailVO groupObj = getParentObj(list, vo.getPid());
                    if (groupObj != null) {
                        detail.setGroupCode(groupObj.getOrgCode());
                        detail.setGroupName(groupObj.getOrgName());
                        ApprovedDiffDetailVO stageObj = getParentObj(list, groupObj.getPid());
                        if (stageObj != null) {
                            detail.setStageCode(stageObj.getOrgCode());
                            detail.setStageName(stageObj.getOrgName());
                            ApprovedDiffDetailVO projectObj = getParentObj(list, stageObj.getPid());
                            if (projectObj != null) {
                                detail.setProjectId(projectId);
                                detail.setProjectCode(projectObj.getOrgCode());
                                detail.setProjectName(projectObj.getOrgName());
                            }
                        }
                    }
                    /**
                     * 产品构成编码
                     */
                    detail.setProductCode(vo.getOrgCode());
                    /**
                     * 产品构成名称
                     */
                    detail.setProductName(vo.getOrgName());
                    /**
                     * 经营方式名称
                     */
                    detail.setBusinessTypeName(vo.getBusinessTypeName());

                    /**
                     * 装修方式名称
                     */
                    detail.setFreeTypeName(vo.getFreeTypeName());

                    /**
                     * 产品属性名称（属性标签）
                     */
                    detail.setProTypeName(vo.getProTypeName());
                }

                setData(vo, detail, id, projectId, versionState, type);
                dataList.add(detail);
            }
        }
        return dataList;
    }

    private ApprovedDiffDetailVO getParentObj(List<ApprovedDiffDetailVO> list, String pid) {
        for (ApprovedDiffDetailVO vo : list) {
            if (vo.getId().equals(pid)) {
                return vo;
            }
        }
        return null;
    }

    private void setData(ApprovedDiffDetailVO vo, PriceApprovalDifferencesDetail detail, String id, String projectId,
                         String versionState, String type) {
        detail.setId(UUIDUtils.create());
        /**
         * 审批单ID
         */
        detail.setBillId(id);
        /**
         * 审批状态
         */
        detail.setState(versionState);
        /**
         * （VS调整前、VS投资版、VS战规版、VS大定价版）
         */
        detail.setVsType(CollectTypeEnum.getValueByKey(type));


        /**
         * 调整后货值-房间套数
         */
        detail.setAfterRoomNum(vo.getAfterRoomNum());
        ;

        /**
         * 调整后货值-房间面积
         */
        detail.setAfterRoomArea(vo.getAfterArea() + "");

        /**
         * 调整后货值-房间均价
         */
        detail.setAfterRoomAvg(vo.getAfterHouseAvgPrice() + "");

        /**
         * 调整后货值-房间金额
         */
        detail.setAfterRoomPrice(vo.getAfterHousePrice() + "");

        /**
         * 调整后货值-车位套数
         */
        detail.setAfterParkingNum(vo.getAfterParkingNum());

        /**
         * 调整后货值-车位均价
         */
        detail.setAfterParkingAvg(vo.getAfterParkingAvgPrice() + "");
        /**
         * 调整后货值-车位金额
         */
        detail.setAfterParkingPrice(vo.getAfterParkingPrice() + "");
        /**
         * VS版本货值-房间套数
         */
        detail.setVsRoomNum(vo.getBeforeRoomNum());
        /**
         * VS版本货值-房间面积
         */
        detail.setVsRoomArea(vo.getBeforeArea() + "");
        /**
         * VS版本货值-房间均价
         */
        detail.setVsRoomAvg(vo.getBeforeHouseAvgPrice() + "");
        /**
         * VS版本货值-房间金额
         */
        detail.setVsRoomPrice(vo.getBeforeHousePrice() + "");
        /**
         * VS版本货值-车位套数
         */
        detail.setVsParkingNum(vo.getBeforeParkingNum());
        /**
         * VS版本货值-车位均价
         */
        detail.setVsParkingAvg(vo.getBeforeParkingAvgPrice() + "");
        /**
         * VS版本货值-车位金额
         */
        detail.setVsParkingPrice(vo.getBeforeParkingPrice() + "");
        /**
         * 货值差异-总货值金额差异
         */
        detail.setTotalDiff(vo.getTotalDiff() + "");
        /**
         * 货值差异-总货值金额差异比（百分比）
         */
        detail.setTotalDiffPer(vo.getTotalDiffPer() + "");
        /**
         * 房源货值差异-金额差异
         */
        detail.setRoomPriceDiff(vo.getPriceDiff() + "");
        /**
         * 房源货值差异-金额差异比（百分比）
         */
        detail.setRoomPriceDiffPer(vo.getPriceDiffPer() + "");
        /**
         * 房源货值差异-均价差异
         */
        detail.setRoomAvgDiff(vo.getAvgPriceDiff() + "");
        /**
         * 房源货值差异-均价差异比（百分比）
         */
        detail.setRoomAvgDiffPer(vo.getAvgPriceDiffPer() + "");
        /**
         * 房源货值差异-面积差异
         */
        detail.setRoomAreaDiff(vo.getAreaDiff() + "");
        /**
         * 房源货值差异-面积差异比（百分比）
         */
        detail.setRoomAreaDiffPer(vo.getAreaDiffPer() + "");
        /**
         * 房源货值差异-套数差异
         */
        detail.setRoomNumDiff(vo.getNumDiff() + "");
        /**
         * 房源货值差异-套数差异比（百分比）
         */
        detail.setRoomNumDiffPer(vo.getNumDiffPer() + "");
        /**
         * 可售车位货值差异-金额差异
         */
        detail.setParkingPriceDiff(vo.getParkingPriceDiff() + "");
        /**
         * 可售车位货值差异-金额差异比（百分比）
         */
        detail.setParkingPriceDiffPer(vo.getParkingPriceDiffPer() + "");
        /**
         * 可售车位货值差异-均价差异
         */
        detail.setParkingAvgDiff(vo.getParkingAvgPriceDiff() + "");
        /**
         * 可售车位货值差异-均价差异比（百分比）
         */
        detail.setParkingAvgDiffPer(vo.getParkingAvgPriceDiffPer() + "");
        /**
         * 可售车位货值差异-车位数差异
         */
        detail.setParkingNumDiff(vo.getParkingNumDiff() + "");
        /**
         * 可售车位货值差异-车位数差异比（百分比）
         */
        detail.setParkingNumDiffPer(vo.getParkingNumDiffPer() + "");
        /**
         * 创建时间
         */
        detail.setCreateTime(LocalDateTime.now());
    }


}
